package com.xbongbong.saas.service.recheck.strategy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.handle.analysis.ContactListAnalysisDataHandler;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.UserAndDepartmentGetDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.common.pojo.CheckRepeatToolHeadPojo;
import com.xbongbong.pro.common.pojo.CheckRepeatToolPojo;
import com.xbongbong.pro.common.pojo.ReCheckSearchResultPojo;
import com.xbongbong.pro.common.pojo.RepeatSearchFieldPojo;
import com.xbongbong.pro.common.pojo.dto.CheckRepeatToolDTO;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.message.constant.WorkOrderPushConstant;
import com.xbongbong.saas.service.recheck.abstracts.RecheckSearchStrategy;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.help.RecheckingRuleHelp;
import com.xbongbong.saas.service.UserTeamService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author jiangren.li
 * @ProjectName xbb-pro
 * @Description: 联系人重复规则实现
 * @date 2022/11/13 10:59
 */
@Service("contactRecheckSearchStrategyImpl")
public class ContactRecheckSearchStrategyImpl implements RecheckSearchStrategy {
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private RecheckingRuleHelp recheckingRuleHelp;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private ContactListAnalysisDataHandler contactListAnalysisDataHandler;

    /**
     * 业务类型
     *
     * @return 业务类型
     */
    @Override
    public Integer type() {
        return XbbRefTypeEnum.CONTACT.getCode();
    }

    /**
     * 查重结果集封装
     * reCheckSearchResultPojo 封装了查重需要透传的参数
     *
     * @param checkRepeatToolDTO
     * @param reCheckSearchResultPojo
     * @return
     * @throws
     * @author lijiangren
     * @date 2022-11-16 14 03
     * @version
     * @since
     */
    @Override
    public CheckRepeatToolPojo repeatResult(CheckRepeatToolDTO checkRepeatToolDTO, ReCheckSearchResultPojo reCheckSearchResultPojo) throws XbbException {
        CheckRepeatToolPojo checkRepeatToolPojo = new CheckRepeatToolPojo();

        String corpid = checkRepeatToolDTO.getCorpid();
        Integer businessType = checkRepeatToolDTO.getBusinessType();
        String userId = checkRepeatToolDTO.getUserId();
        Set permSet = checkRepeatToolDTO.getLoginUser().getPermSet();
        Long firstFormId = reCheckSearchResultPojo.getFirstFormId();
        List<RepeatSearchFieldPojo> repeatSearchFieldList = reCheckSearchResultPojo.getRepeatSearchFieldList();
        List<PaasFormDataEntityExt> paasFormDataEntityList = reCheckSearchResultPojo.getPaasFormDataEntityList();
        List<PaasProcessDataEntity> partPaasProcessData = reCheckSearchResultPojo.getPartPaasProcessData();
        PaasFormEntityExt paasFormEntityExt = reCheckSearchResultPojo.getPaasFormEntityExt();

        PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(firstFormId, corpid);
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getAllSubFormExplainMap(explainEntity.getExplains());
        List<String> recheckResultField = recheckingRuleHelp.getRecheckResultField(firstFormId, checkRepeatToolDTO, explainMap);

        // 客户-表单映射关系
        List<Long> customerIdIn = new ArrayList<>();
        for (PaasFormDataEntityExt entity : paasFormDataEntityList) {
            customerIdIn.add(entity.getDataId());
        }

        UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
        BeanUtil.copyProperties(checkRepeatToolDTO, userAndDepartmentGetDTO);
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userTeamService.getUserIdMap(customerIdIn, corpid, businessType, false, mainUserMap, coUserMap);
        boolean formPermission = true;
        if (!recheckingRuleHelp.validatePermission(paasFormEntityExt,checkRepeatToolDTO.getLoginUser())) {
            formPermission = false;
        }
        //查重字段关系用于前端高亮
        if (CollectionsUtil.isNotEmpty(repeatSearchFieldList)) {
            repeatSearchFieldList.removeIf(item -> !Objects.equals(firstFormId, item.getFormId()));
            checkRepeatToolPojo.setHighLightFieldList(repeatSearchFieldList);
        }

        checkRepeatToolPojo.setFormId(paasFormEntityExt.getId());
        checkRepeatToolPojo.setFormName(paasFormEntityExt.getName());
        checkRepeatToolPojo.setSaasMark(paasFormEntityExt.getSaasMark());
        //封装结果集的头部
        List<CheckRepeatToolHeadPojo> headList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (String restAttr : recheckResultField) {
            CheckRepeatToolHeadPojo checkRepeatToolHeadPojo = new CheckRepeatToolHeadPojo();
            //封装head
            if (Objects.equals(restAttr, FieldTypeEnum.OPTION.getAlias())) {
                checkRepeatToolHeadPojo.setAttr(FieldTypeEnum.OPTION.getAlias());
                checkRepeatToolHeadPojo.setAttrName("操作");
                headList.add(checkRepeatToolHeadPojo);
            } else if (Objects.equals(restAttr, "position")) {
                checkRepeatToolHeadPojo.setAttr("position");
                checkRepeatToolHeadPojo.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.LOCATION));
                headList.add(checkRepeatToolHeadPojo);
            } else {
                FieldAttrEntity fieldAttrEntity = explainMap.get(restAttr);
                if (Objects.nonNull(fieldAttrEntity)) {
                    checkRepeatToolHeadPojo.setAttr(fieldAttrEntity.getAttr());
                    checkRepeatToolHeadPojo.setAttrName(fieldAttrEntity.getAttrName());
                    checkRepeatToolHeadPojo.setFieldType(fieldAttrEntity.getFieldType());
                    headList.add(checkRepeatToolHeadPojo);
                }
            }
        }
        checkRepeatToolPojo.setHeadList(headList);
        List<Map> dataList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        formDataListVO.setPaasFormDataESList(paasFormDataEntityList);
        formDataListVO.setBusinessType(checkRepeatToolDTO.getBusinessType());
        List<FieldAttrEntity> explainList = JSONArray.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
        formDataListVO.setHeadList(explainList);
        formDataListVO.setExplainMap(ExplainUtil.getAllSubFormExplainMap(explainEntity.getExplains()));
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(checkRepeatToolDTO, formDataListDTO);
        formDataListDTO.setFormId(firstFormId);
        contactListAnalysisDataHandler.analysisDataList(formDataListDTO, formDataListVO);

        for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
            JSONObject data = entity.getData();
            Map resultMap = new HashMap(recheckResultField.size());
            for (String restAttr : recheckResultField) {
                if (Objects.equals(restAttr, "position")) {
                    resultMap.put(restAttr, recheckingRuleHelp.getPositionByBusinessType(businessType,entity));
                } else if (Objects.equals(restAttr, "option")) {
                    Boolean addTeam = true;
                    List<String> mainUserIdList = mainUserMap.getOrDefault(entity.getDataId(),new ArrayList<>());
                    List<String> coUserIdList = coUserMap.getOrDefault(entity.getDataId(),new ArrayList<>());
                    // 判断有无 "查重-加入团队" 权限
                    if (!permSet.contains(ProPermissionAliasEnum.CONTACT_REPEAT_JOIN_TEAM.getAlias())) {
                        addTeam = false;
                    }
                    if (mainUserIdList.contains(userId) || coUserIdList.contains(userId)) {
                        addTeam = false;
                    }
                    if (Objects.equals(entity.getFlowStatus(), FlowStatusEnum.APPROVAL_PENDING.getType()) || Objects.equals(entity.getFlowStatus(), FlowStatusEnum.IN_APPROVAL.getType())) {
                        addTeam = false;
                    }
                    //判断表单模版权限
                    if (!formPermission) {
                        addTeam = false;
                    }
                    if (addTeam){
                        ButtonPojo buttonPojo = new ButtonPojo();
                        buttonPojo.setAttr("addTeam");
                        buttonPojo.setValue(I18nMessageUtil.getMessage(WorkOrderPushConstant.WORK_ORDER_TEAM_ADD_TITLE));
                        resultMap.put(restAttr,Collections.singletonList(buttonPojo));
                        resultMap.put("isAddTeam",true);
                    }
                }else {
                    recheckingRuleHelp.dealTimeFormat(explainMap, data, resultMap, restAttr);
                }

            }
            resultMap.put("subBusinessType", recheckingRuleHelp.getSubBusinessType(businessType,entity));
            resultMap.put("flowStatus", entity.getFlowStatus());
            resultMap.put("id", entity.getId());
            resultMap.put("del", entity.getDel());
            dataList.add(resultMap);
        }
        if (dataList.size() <= BasicConstant.TEN && partPaasProcessData.size() > 0) {
            recheckingRuleHelp.dealApprovalDataResult(checkRepeatToolDTO,dataList,recheckResultField,partPaasProcessData,explainMap);
        }

        checkRepeatToolPojo.setDataList(dataList);
        return checkRepeatToolPojo;
    }

}
